import User.User;
import User.Duser;

import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "AddEmail", urlPatterns = "/AddEmail")
public class AddEmail extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        addEmail(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
       addEmail(request, response);
    }
    protected void addEmail(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Duser duser = (Duser) request.getSession().getAttribute("DGUT");
        String email = request.getParameter("add_email");
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyDSTest");
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction entityTransaction = entityManager.getTransaction();
        if (email != null) {
            User user1 = null;
            boolean flag = true;
            Query query=entityManager.createNativeQuery("select * from USER",User.class);
            List<User> list=query.getResultList();
            if (list != null) {
                Iterator<User> it = list.iterator();
                while (it.hasNext()) {
                    user1 = (User)it.next();
                    if(user1.getEmail().equals(email))
                        flag = false;
                }
            }
            if (flag) {
                duser.setEmail(email);
                if (!Treatment.writeDgut(duser)) {
                    response.sendRedirect("/error.jsp");
                }
                User user = new User(duser.getName(), duser.getEmail(), duser.getPasswd(), duser.getId(), duser.getImg());
                try {
                    entityTransaction.begin();
                    entityManager.persist(user);
                    entityTransaction.commit();
                } catch (Exception e) {
                    System.out.println("莞工登陆用户本地注册写入失败！");
                    response.sendRedirect("/error.jsp");
                }
                request.getSession().setAttribute("SELF", user);
                request.getSession().setAttribute("DGUT", duser);
                response.sendRedirect("/user.jsp");
            }
            else
            {
                System.out.println("邮箱重复！");
                response.sendRedirect("/error.jsp");
            }
        }
    }
}
